import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
import styles from "./options.module.less";

// 配置文件格式
// config: {
//   urls: []
// }

const defaultRefreshTime = 4 * 60 * 1000; //5 分钟刷一次

function Options() {
  const [urls, setUrls] = useState();
  const [refreshTime, setRefreshTime] = useState(defaultRefreshTime);

  useEffect(() => {
    chrome.storage.sync.get(["config"], ({ config }) => {
      let urls = config.urls;
      if (!urls) urls = [];
      setUrls(urls);
      if (config.refreshTime) setRefreshTime(config.refreshTime);
    });
  }, []);

  const saveConfig = () => {
    chrome.storage.sync.set({ config: { urls, refreshTime } }, function () {
      console.log("Saved successfully!");
    });
  };

  // 表达式
  const onAdd = () => {
    const newUrls = urls.slice();
    newUrls.push("");
    setUrls(newUrls);
  };

  const onChangeIndex = (event, index) => {
    const newUrls = urls.slice();
    newUrls[index] = event.target.value;
    setUrls(newUrls);
  };

  const onDel = (index) => {
    const newUrls = urls.slice();
    newUrls.splice(index, 1);
    setUrls(newUrls);
  };

  // 刷新时间
  const onChangeRefreshTime = (event) => {
    setRefreshTime(event.target.value);
  };

  const renderLine = (urls) =>
    urls &&
    urls.map((url, index) => (
      <li className={styles.line}>
        <input value={url} onChange={(event) => onChangeIndex(event, index)}></input>
        <button onClick={() => onDel(index)}>删除</button>
      </li>
    ));

  return (
    <div className={styles.options}>
      <div className={styles.wrapper}>
        <ul className={styles.list}>{renderLine(urls)}</ul>
        <div>
          <input value={refreshTime} onChange={onChangeRefreshTime}></input>
        </div>
        <div className={styles.btnBar}>
          <button onClick={onAdd}>添加表达式</button>
          <button onClick={saveConfig}>保存</button>
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<Options />);
